define(["jquery",
        "jquery-ui",
        "domReady",
        "jquery-editable",
        "jquery-wysiwyg",
        "jquery-editable-wysiwyg",
        "jquery-tinymce"],
        function($){
    "use strict";
   
   // save the results
   $(".gcb_a_disable_edit").click(function(){
	   console.log("Disable Edits");
	   $(".gcb_a_editable_area").editable("disable");
	   $(".gcb_a_editable").editable("disable");
	   $(".gcb_a_control").hide();
	   $(this).parents('.gcb_a_edit_container').find('.gcb_a_edit_controls').hide();
	   $(this).parents('.gcb_a_edit_container').find('.gcb_a_enable_edit').show();

   });

   var show_error = function(v) {
	   alert(v);
   };
   
   var activate_editable = function(editable) {
	   var url = $(editable).attr("gcb-a-action");
	   if ( url !== undefined && url !== false ) {
		   $(editable).editable(url,{ 
		       cancel    : 'Cancel',
		       submit    : 'OK',
	    	   onblur    : 'ignore',
	    	   tooltip   : 'Click to edit...'
		   });
	   } else {
		   $(editable).editable(function(value, settings) {
			   $(editable).addClass("gcb_a_modified");
			   return value;	   
		   }, { 
		       cancel    : 'Cancel',
		       submit    : 'OK',
	    	   onblur    : 'ignore',
		       tooltip   : 'Click to edit...'
		   });
	   }
   };

   
   var activate_editable_area = function(editable) {
	   var url = $(editable).attr("gcb-a-action");
	   if ( url !== undefined && url !== false ) {
		   $(editable).editable(url,{ 
	    	   type      : 'wysiwyg',
	    	   onblur    : 'ignore',
	           cancel    : 'Cancel',
	           submit    : 'OK',
	           tooltip   : 'Click to edit...'
	       });
	   } else {
	       $(editable).editable(function(value, settings){
		       $(editable).addClass("gcb_a_modified");
		       return value;
	       }, { 
	    	   type      : 'wysiwyg',
	    	   onblur    : 'ignore',
	           cancel    : 'Cancel',
	           submit    : 'OK',
	           tooltip   : 'Click to edit...'
	       });
	   }
   };
   
   var enable_edits = function(container) {
	   $('.editable > a', container).bind('click', function() {
	       $(this).parent().trigger('click');
	       return false; 
	   });
	   $(".gcb_a_editable_area", container).each(function() {
		   activate_editable_area(this);
	   });

	   $(".gcb_a_editable", container).each(function() {
		   activate_editable(this);
	   });
   }

   // collect the data from all input elements in the form.
   // render the template
   // post to the url not false
   // append to the target.
   var save_dialog = function(dialog, template, url, target){
	   var postdata = {}
	   $(dialog).find('input:text, input:hidden, input:radio:checked, input:checkbox:checked, textarea').each(function() {
		   console.log("Field "+$(this).attr("name")+" value "+$(this).val());
		   postdata[$(this).attr("name")] = $(this).val();
	   });
	   $(dialog).find('select').each(function() {
		   var v = [];
		   $(this).find('option:selected').each(function(){
			   v.push($(this).val());
		   });
		   console.log("Field "+$(this).attr("name")+" value "+v.join(","));
		   postdata[$(this).attr("name")] = v.join(",");
	   });
	   if ( url !== false ) {
		   $.post(url, postdata).success(function(){
			   $(template).tmpl(postdata).appendTo(target);
			   enable_edits($(target).children().last());
		   }).error(function(data){
			   show_error(data);
		   });		   
	   } else {
		   $(template).tmpl(postdata).appendTo(target);
		   enable_edits($(target).children().last());
	   }
   };
   

   // make the interface editable, if this has not been done, editors are attached and enabled.
   // if not, editors are just enabled.
   // all other editing controls are shown.
   $(".gcb_a_enable_edit").click(function(){
	   console.log("Enable Edits");
	   if (!$(this).hasClass("gcb_a_editing_init") ) {
		   $(this).addClass("gcb_a_editing_init");
		   /* Handle links inside editable area. */
		   $('.editable > a').bind('click', function() {
		       $(this).parent().trigger('click');
		       return false; 
		   });
		   $(".gcb_a_editable_area").each(function() {
			   activate_editable_area(this);
		   });

		   $(".gcb_a_editable").each(function() {
			   activate_editable(this);
		   });
	   }
	   $(".gcb_a_editable_area").editable("enable");
	   $(".gcb_a_editable").editable("enable");
	   $(".gcb_a_control").show();
	   $(this).hide();
	   $(this).parents('.gcb_a_edit_container').find('.gcb_a_edit_controls').show();
   });
   
   $(".gcb_a_dialog").each(function() {
	   var title = $(this).attr("title");
	   var width = $(this).attr("width");
	   var container = $(this).parents(".gcb_a_control_container");
	   var template_el = $(container).find(".gcb_a_template");
	   var template = $("#"+$(template_el).attr("gcb-a-template"));
	   var action = $(template_el).attr("gcb-a-action");
	   var target = $("#"+$(template_el).attr("gcb-a-target"));
	   $(this).dialog({
		   autoOpen: false,
		   modal: true,
		   title : title,
		   width : width,
		   buttons : {
			   "Save" : function() {
				   save_dialog(this, template, action, target);
				   $(this).dialog("close");
			   },
			   "Cancel" : function() {
				   $(this).dialog("close");
			   }
		   }
	   });
   });
   
   $(".gcb_a_open_dialog").click(function(){
	  var dialog = $(this).attr("gcb-a-dialog");
	  $('#'+dialog).dialog("open");
   });
   
   
   
   
   $(".gcb_a_editable_wysiwyg").tinymce({
		   // Location of TinyMCE script
           script_url : '/assets/js/libs/tiny_mce/tiny_mce.js',

           // General options
           theme : "advanced",
           theme_advanced_buttons1 : "formatselect,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,image, media,code,|,hr,removeformat,|,sub,sup,iespell",
           theme_advanced_toolbar_location : "top",
           theme_advanced_toolbar_align : "left",
           plugins : "advhr,advimage,advlink,inlinepopups,media",
          // theme_advanced_statusbar_location : "bottom",
          // theme_advanced_resizing : true,
           /*
           plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            
           // Theme options
           theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
           theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
           theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,",
           theme_advanced_buttons4 : "cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
           theme_advanced_toolbar_location : "top",
           theme_advanced_toolbar_align : "left",
           theme_advanced_statusbar_location : "bottom",
           theme_advanced_resizing : true,
            */

           /*
           // Example content CSS (should be your site CSS)
           content_css : "/assets/css/main.css",
		   */
           /*
           // Drop lists for link/image/media/template dialogs
           template_external_list_url : "lists/template_list.js",
           external_link_list_url : "lists/link_list.js",
           external_image_list_url : "lists/image_list.js",
           media_external_list_url : "lists/media_list.js",
	       */
           /*
           // Replace values for the template plugin
           template_replace_values : {
                   username : "Some User",
                   staffid : "991234"
           }
           */
       });
   
  

});